<?php
/**
 * M1我的跟单
 */

namespace app\admin\model;

use think\Db;
use app\v2\model\Order;
use app\v2\model\Apply;

class Soso extends Common
{
    protected $name = 'apply';

    /**
     *  搜一搜
     * @author cxr <1481746137@qq.com>
     * @param $uid
     * @param $keywords
     * @param int $page
     * @param int $limit
     * @param $valuedate
     * @param $startdate
     * @param $enddate
     * @param string $os
     * @param string $status
     * @param string $employee
     * @return mixed
     */
    public function getDataList($uid, $keywords, $page = 1, $limit = 15, $valuedate, $startdate, $enddate, $os = '', $status = "",$employee = '',$export = false)
    {

            //排序
            $order = 'status_sort desc,auth_type desc,id desc';
            $field = '*,(
                CASE STATUS
                WHEN 0 THEN
                    10
                WHEN 2 THEN
                    9
                WHEN 9 THEN
                    8
                WHEN 3 THEN
                    7
                WHEN 4 THEN
                    6
                WHEN 12 THEN
                    5
                WHEN 5 THEN
                    4
                WHEN 6 THEN
                    3
                WHEN 10 THEN
                    2
                WHEN 11 THEN
                    1
                END
            ) AS status_sort';

            $map = array();
            if($employee){
                $map['check_aid|merchandiser|merchandiser2|mtwo_admin_user_id|treasurer'] = ['eq', $employee];
            }
            if ($startdate) {
                $map['time'] = array('BETWEEN', [$startdate, $enddate]);  // 时间段
            }
            if ($os) {
                $map['os'] = $os;
            }
            if ($keywords) {
                $map['phone|order_number|name'] = ['like', '%' . $keywords . '%'];
            }

            if (!is_null($status) && in_array($status, [0, 2, 3, 4, 5, 9, 10, 11, 12])) {
                $map['status'] = $status;
            }

            $dataCount = $this->where($map)->count();
            $this->field($field)
                ->where($map)
                ->order($order);

            if ($export == true && ($keywords || $startdate || $employee)) {
                $list = $this->select();
            } else {
                $list = $this->page($page, $limit)->select();
            }

            foreach ($list as $key => $value) {
                $list[$key]['info'] = $this->statusInfo($list[$key]['status']);          //状态信息

                $list[$key]['already_money'] = self::alreadyRepay($value, $list[$key]['status']);//已还总金额
                $list[$key]['repay'] = $this->getRepay($list[$key]['status'], $value, $list[$key]['already_money']);//应还总金额
                $list[$key]['surplus'] = $this->getSurplus( $list[$key]['repay'],$list[$key]['status'] );//剩余应还金额

                $list[$key]['user_admin1'] = $this->getNameById($value['check_aid']);      //初审员
                $list[$key]['user_admin2'] = $this->getNameById($value['check2_aid']);     //复审员
                $list[$key]['user_admin3'] = $this->getNameById($value['merchandiser']);   //跟单员M0
                $list[$key]['user_admin4'] = $this->getNameById($value['merchandiser2']);  //催收员M1
                $list[$key]['user_admin5'] = $this->getNameById($value['mtwo_admin_user_id']);  //催收员M2
                $list[$key]['user_admin6'] = $this->getNameById($value['treasurer']);      //财务员

                $list[$key]['delay_transfer_date'] = $this->transferTime($value);  //延时移交时间
                $list[$key]['this_delay_money'] = $this->getDelayMoney($value);
                //是否留案
                $list[$key]['is_liuan'] = $this->isLiuan($value);
            }

            // 后台用户
            $employee = AdminGroup::all(function($query){
                        return $query->field('title as label,id as value,id')->where(['id' => ['in',[21,23,24,25,26,31]]]);
                  },['children']);

            $data['list'] = $list;
            $data['dataCount'] = $dataCount;
            $data['employee'] = $employee;
            return $data;

    }

    /**
     *  导出Excel,返回地址
     * @author cxr <1481746137@qq.com>
     * @param $keywords
     * @param $page
     * @param $limit
     * @param $valuedate
     * @param $os
     * @param $status
     * @return string
     */
    public function export($uid, $keywords, $page = 1, $limit = 15, $valuedate, $startdate, $enddate, $os = '', $status = "",$employee = '')
    {
        $data =  $this->getDataList($uid, $keywords, $page, $limit, $valuedate, $startdate, $enddate, $os , $status ,$employee ,true);
        $data = modelo2array( $data['list']);
        $arrdata[] = ['排序','申请时间','姓名','状态,','借款','期限','手机号码','初审员','初审时间','复审员','复审时间','M1回访员','回访时间','还款日期','机型'];
        $keys = ['seq','time','name','status','money','period','phone','user_admin1','check_time','user_admin2','check2_time','merchandiser','monepassdate','appoint_time','mobile_type'];
        $filter =  $this->filterVal($data,$keys);
        $arrdata = array_merge ($arrdata,  $filter );

        //var_dump($arrdata);exit;
        $path = $this->create_xls($arrdata,'soso.xls');
        return $path;

    }

    /**
     * 按Key过滤排序
     * @author cxr <1481746137@qq.com>
     * @param $arr
     * @param $keys
     * @return mixed
     */
    public function filterVal($arr,$keys){
        foreach($keys as $k=>$v)
            foreach($arr as $k2=>$v2)
                $new_array[$k2][$v] = $arr[$k2][$v];
        return $new_array;
    }



    /**
     * 创建财务excel
     * @author cxr <1481746137@qq.com>
     * @param $data
     * @param string $filename
     * @return string
     * @throws \PHPExcel_Exception
     * @throws \PHPExcel_Reader_Exception
     * @throws \PHPExcel_Writer_Exception
     */
    public function create_xls($data,$filename='soso.xls'){
        ini_set('max_execution_time', '0');
        $filename=str_replace('.xls', '', $filename).'.xls';
        $phpexcel = new \PHPExcel();
        $phpexcel->getProperties()
            ->setCreator("Maarten Balliauw")
            ->setLastModifiedBy("Maarten Balliauw")
            ->setTitle("Office 2007 XLSX Test Document")
            ->setSubject("Office 2007 XLSX Test Document")
            ->setDescription("Test document for Office 2007 XLSX, generated using PHP classes.")
            ->setKeywords("office 2007 openxml php")
            ->setCategory("Test result file");
        $phpexcel->getActiveSheet()->fromArray($data);
        $phpexcel->getActiveSheet()->setTitle('Sheet1');
        $phpexcel->setActiveSheetIndex(0);
        $objwriter = \PHPExcel_IOFactory::createWriter($phpexcel, 'Excel5');
        $dir = dirname(__FILE__);
        $objwriter->save(ROOT_PATH.'/public/'.$filename);
        return  '/public/'.$filename;
    }




    /**
     * 自动移交时间
     * @author cxr <1481746137@qq.com>
     */
    public function transferTime($value){

        if(!$value['overdue_date'])
            return;

        $will = !$this->isLiuan($value) ? $value['delay_transfer_date'] : $value['appoint_time'];
        $onTime = strtotime('+1 day', strtotime($will));
//        $time =  date('Y-m-d H:i:s', $onTime);

        $time =  date('Y-m-d', $onTime);
        $time = date('Y-m-d H:i:s',strtotime('+23hours',strtotime( $time ) + 3540));

        return $time;
    }

    /**
     * 能否留案
     * @author cxr <1481746137@qq.com>
     */
    public function isLiuan($value){
        if(empty($value['delay_transfer_date'])){
            return true;
        }
        $date = strtotime($value['delay_transfer_date']);
        $time = date('Y-m-d',$date);
        if(strtotime($time) <= strtotime($value['appoint_time']) ){
            return true;
        }
        return false;
    }

    /**
     * 已还金额
     * @author cxr <1481746137@qq.com>
     * @param $applyid
     * @param $status
     * @param $total
     * @return float|int
     */
    static public function alreadyRepay($value, $status)
    {
        if (in_array($status, [5])) {

            return $value['actual_money'] + $value['part_repay'];
        }
        #已还金额 = 每次待还金额
        return $value['actual_money'] + $value['part_repay'];


    }


    /**
     * 移交客户
     * @author   湛慧平 <1013619199@qq.com>
     * @DateTime 2017-08-10
     * @param
     */
    public function Transferinfo($param)
    {
        $admin_uid = $GLOBALS['userInfo']['id'];
        $transfer_info = $param['opinion'];
        $uid = $param['uid'];
        $id = $param['id'];
        $map['id'] = $id;
        $date = date("Y-m-d H:i:s", time());

        $data = ['transfer_info' => $transfer_info, 'transfer' => 1, 'm1_yijiao_date' => $date];
        $admin_data = ['uid' => $uid, 'authstatus' => 4, 'admin_user_id' => $admin_uid, 'status' => 2, 'apply_id' => $id, 'date' => $date];
        $admin_info = Db::name('admin_user_clien')->insert($admin_data);
        if (!$admin_info) {
            $this->error = "没有保存";
            return false;
        }

        $info = $this->save($data, $map);
        if (!$info) {
            $this->error = "移交失败";
            return false;
        }

        return true;

    }

    /**
     * 延时移交/留案
     * @author cxr <1481746137@qq.com>
     * @param $param
     * @return bool
     * @throws \think\exception\DbException
     */
    public function delayTransfer($param)
    {

        $info = self::get(['id' => $param['id']]);
//        $hours = config('DELAY_TRANSFER_HOUR');
        $hours = $param['hours'] * 24;

        if ($this->isLiuan($info)) {
            $delay = strtotime("+{$hours} hours", strtotime($info->appoint_time));
        } else {
//            $delay = strtotime("+{$hours} hours", strtotime($info->delay_transfer_date));
            $this->error = "已留案,不能重复留案!";
            return false;
        }

        $date = date('Y-m-d H:i:s', $delay);
        $info->delay_transfer_date = $date;

        if (!$info->save()) {
            $this->error = "延时移交失败";
            return false;
        }
        return true;
    }



    /**
     * 延期预览金额及日期
     * @author cxr <1481746137@qq.com>
     * @param $id
     * @return mixed
     */
    public function getdelay($param){
        
        if(!$param['smsVerification_s'] || strlen($param['smsVerification_s']) != 4 ){
            return resultArray(["error" => '验证码错误1']);
        }
        $user_id = $GLOBALS['userInfo']['id'];
        $res = Db::name('smsverification')->where(['user_id'=>$user_id])->field('smsVerification,create_date')->find();
        if($param['smsVerification_s'] != $res['smsVerification'] || (time() > (strtotime($res['create_date'])+(config('sms_aging')['sms_aging'])))){
              return resultArray(["error" => '验证码错误2']);
        }

        $res = $this->where('id', $param['id'])->find();

        if($res['zhangqi']==1 && $param['days']==7){
            $this->error='不能重复展期';
            return false;
        }

        #延期种类对应金额（4种 1 2 3 7） 2018 3/9
        $delayMoney = model('v2/Apply');
        $delayMoneyOrder = $delayMoney->delayMoney($res->toArray(),$param['days']);
        if(!$delayMoneyOrder){
            $this->error= $delayMoney->getError();
            return false;
        }

         $appoint_time = $res['appoint_time'];   //约定还款时间
         $period = $param['days']; //借款周期

        $period = $param['days']; //借款周期

        if(strtotime(date("Y-m-d H:i:s", strtotime($appoint_time))) > strtotime(date("Y-m-d H:i:s"))){
            $startTime = strtotime( $appoint_time );
            $data['type'] = '正常';
        }else{
            $startTime =  time();
            $data['type'] = '逾期';
        }
        $data['delayDate'] = date("Y-m-d H:i:s", $startTime + $period*24*3600);
         $data['delayDate2']  = date('Y-m-d H:i:s', $appoint_time + $period*24*3600); //延期后归还日期


         $data['delayMoney'] = $delayMoneyOrder['money_order']; //延期后归还金额

        return $data;
    }




}